package com.ilink.groundservice.service.impl.Literature;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.Literature.AiXLiterature;
import com.ilink.groundservice.entity.PO.Literature.AiXLiteratureFavorite;
import com.ilink.groundservice.entity.VO.AiX.AiXLiteratureResponse;
import com.ilink.groundservice.mapper.Literature.AiXLiteratureFavoriteMapper;
import com.ilink.groundservice.mapper.Literature.AiXLiteratureMapper;
import com.ilink.groundservice.mapper.AiX.AiXTagConnectMapper;
import com.ilink.groundservice.service.Literature.AiXLiteratureService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXLiteratureFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXLiteratureInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXLiteratureUpdateRequest;
import com.ilink.ilinkcommon.exception.BadRequestException;
import com.ilink.ilinkcommon.exception.BizIllegalException;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.domain.R;
import org.springframework.web.multipart.MultipartFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AiXLiteratureServiceImpl implements AiXLiteratureService {

    private final AiXLiteratureMapper literatureMapper;
    private final AiXLiteratureFavoriteMapper favoriteMapper;
    private final OssService ossService;
    private final AiXTagConnectMapper tagConnectMapper;

    @Override
    public IPage<AiXLiteratureResponse> getLiteratureList(AiXLiteratureFilterRequest request, String userId) {
        Page<AiXLiteratureResponse> page = new Page<>(request.getPage(), request.getSize());
        // 如果有标签筛选，使用标签筛选方法；否则使用原有方法
        IPage<AiXLiteratureResponse> result;
        if (request.getTag() != null && !request.getTag().trim().isEmpty()) {
            result = literatureMapper.selectLiteraturePageByTag(page, request, userId);
        } else {
            result = literatureMapper.selectLiteraturePage(page, request, userId);
        }
        
        // 为每个文献设置标签列表
        result.getRecords().forEach(literature -> {
            List<String> tags = literatureMapper.selectLiteratureTags(literature.getLiteratureId());
            literature.setTags(tags);
        });
        
        return result;
    }

    @Override
    public AiXLiteratureResponse getLiteratureById(Long literatureId, String userId) {
        if (literatureId == null) {
            throw new BizIllegalException("文献ID不能为空");
        }
        
        AiXLiteratureResponse response = literatureMapper.selectLiteratureById(literatureId, userId);
        if (response == null) {
            throw new BizIllegalException("文献不存在");
        }
        
        // 设置标签列表
        List<String> tags = literatureMapper.selectLiteratureTags(literatureId);
        response.setTags(tags);
        
        // 增加查看次数
        incrementViewCount(literatureId);
        
        return response;
    }

    @Override
    @Transactional
    public Long insertLiterature(AiXLiteratureInsertRequest request) {
        if (request == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        
        // 使用雪花算法生成文献ID
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 3);
        
        AiXLiterature literature = BeanUtils.copyBean(request, AiXLiterature.class);
        literature.setLiteratureId(idGenerator.nextId());
        literature.setViewCount(0);
        literature.setDownloadCount(0);
        literature.setCreatedAt(LocalDateTime.now());
        literature.setUpdatedAt(LocalDateTime.now());
        
        // 处理PDF文件上传
        if (request.getPdfFile() != null && !request.getPdfFile().isEmpty()) {
            String pdfUrl = ossService.uploadFileAndGetUrl(request.getPdfFile(), "study-square-migrate", "literature/pdf_" + System.currentTimeMillis() + "_" + request.getPdfFile().getOriginalFilename());
            literature.setPdfUrl(pdfUrl);
        }
        
        // 处理封面图片上传
        if (request.getCoverFile() != null && !request.getCoverFile().isEmpty()) {
            String coverUrl = ossService.uploadFileAndGetUrl(request.getCoverFile(), "study-square-migrate", "literature/cover_" + System.currentTimeMillis() + "_" + request.getCoverFile().getOriginalFilename());
            literature.setCoverUrl(coverUrl);
        }
        
        int result = literatureMapper.insert(literature);
        if (result <= 0) {
            throw new BizIllegalException("文献创建失败");
        }
        
        return literature.getLiteratureId();
    }

    @Override
    @Transactional
    public void updateLiterature(AiXLiteratureUpdateRequest request) {
        if (request == null || request.getLiteratureId() == null) {
            throw new BizIllegalException("请求参数不能为空");
        }
        
        AiXLiterature existingLiterature = literatureMapper.selectById(request.getLiteratureId());
        if (existingLiterature == null) {
            throw new BizIllegalException("文献不存在");
        }
        
        AiXLiterature literature = BeanUtils.copyBean(request, AiXLiterature.class);
        literature.setUpdatedAt(LocalDateTime.now());
        
        // 处理PDF文件上传
        if (request.getPdfFile() != null && !request.getPdfFile().isEmpty()) {
            String pdfUrl = ossService.uploadFileAndGetUrl(request.getPdfFile(), "study-square-migrate", "literature/pdf_" + System.currentTimeMillis() + "_" + request.getPdfFile().getOriginalFilename());
            literature.setPdfUrl(pdfUrl);
        }
        
        // 处理封面图片上传
        if (request.getCoverFile() != null && !request.getCoverFile().isEmpty()) {
            String coverUrl = ossService.uploadFileAndGetUrl(request.getCoverFile(), "study-square-migrate", "literature/cover_" + System.currentTimeMillis() + "_" + request.getCoverFile().getOriginalFilename());
            literature.setCoverUrl(coverUrl);
        }
        
        int result = literatureMapper.updateById(literature);
        if (result <= 0) {
            throw new BizIllegalException("文献更新失败");
        }
    }

    @Override
    @Transactional
    public void deleteLiterature(Long literatureId) {
        if (literatureId == null) {
            throw new BizIllegalException("文献ID不能为空");
        }
        
        AiXLiterature literature = literatureMapper.selectById(literatureId);
        if (literature == null) {
            throw new BizIllegalException("文献不存在");
        }
        
        int result = literatureMapper.deleteById(literatureId);
        if (result <= 0) {
            throw new BizIllegalException("文献删除失败");
        }
    }

    @Override
    public List<AiXLiteratureResponse> getRecommendedLiteratures(Integer limit, String userId) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        List<AiXLiteratureResponse> results = literatureMapper.selectRecommendedLiteratures(limit, userId);
        
        // 为每个文献设置标签列表
        results.forEach(literature -> {
            List<String> tags = literatureMapper.selectLiteratureTags(literature.getLiteratureId());
            literature.setTags(tags);
        });
        
        return results;
    }

    @Override
    public List<AiXLiteratureResponse> getPopularLiteratures(Integer limit, String userId) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        List<AiXLiteratureResponse> results = literatureMapper.selectPopularLiteratures(limit, userId);
        
        // 为每个文献设置标签列表
        results.forEach(literature -> {
            List<String> tags = literatureMapper.selectLiteratureTags(literature.getLiteratureId());
            literature.setTags(tags);
        });
        
        return results;
    }

    @Override
    public IPage<AiXLiteratureResponse> searchLiteratures(String query, String searchType, Integer page, Integer size, String userId) {
        if (query == null || query.trim().isEmpty()) {
            throw new BizIllegalException("搜索关键词不能为空");
        }
        
        Page<AiXLiteratureResponse> pageQuery = new Page<>(page, size);
        IPage<AiXLiteratureResponse> result = literatureMapper.searchLiteratures(pageQuery, query.trim(), searchType, userId);
        
        // 为每个文献设置标签列表
        result.getRecords().forEach(literature -> {
            List<String> tags = literatureMapper.selectLiteratureTags(literature.getLiteratureId());
            literature.setTags(tags);
        });
        
        return result;
    }

    @Override
    public List<String> getAllLiteratureTags(Long areaId) {
        return tagConnectMapper.getAllLiteratureTags(areaId);
    }

    @Override
    @Transactional
    public void favoriteLiterature(Long literatureId, String userId) {
        if (literatureId == null) {
            throw new BizIllegalException("文献ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        // 检查文献是否存在
        AiXLiterature literature = literatureMapper.selectById(literatureId);
        if (literature == null) {
            throw new BizIllegalException("文献不存在");
        }
        
        // 检查是否已收藏
        AiXLiteratureFavorite existingFavorite = favoriteMapper.selectByUserIdAndLiteratureId(userId, literatureId);
        if (existingFavorite != null) {
            throw new BizIllegalException("该文献已被收藏");
        }
        
        // 创建收藏记录
        SnowflakeIdGenerator favoriteIdGenerator = new SnowflakeIdGenerator(1, 4);
        
        AiXLiteratureFavorite favorite = new AiXLiteratureFavorite();
        favorite.setFavoriteId(favoriteIdGenerator.nextId());
        favorite.setUserId(userId);
        favorite.setLiteratureId(literatureId);
        favorite.setCreatedAt(LocalDateTime.now());
        
        int result = favoriteMapper.insert(favorite);
        if (result <= 0) {
            throw new BizIllegalException("收藏文献失败");
        }
    }

    @Override
    @Transactional
    public void unfavoriteLiterature(Long literatureId, String userId) {
        if (literatureId == null) {
            throw new BizIllegalException("文献ID不能为空");
        }
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        int result = favoriteMapper.deleteByUserIdAndLiteratureId(userId, literatureId);
        if (result <= 0) {
            throw new BizIllegalException("取消收藏失败，可能该文献未被收藏");
        }
    }

    @Override
    public IPage<AiXLiteratureResponse> getFavoriteLiteratures(Integer page, Integer size, String userId) {
        if (userId == null) {
            throw new BizIllegalException("用户ID不能为空");
        }
        
        Page<AiXLiteratureResponse> pageQuery = new Page<>(page, size);
        IPage<AiXLiteratureResponse> result = favoriteMapper.selectFavoriteLiteratures(pageQuery, userId);
        
        // 为每个文献设置标签列表
        result.getRecords().forEach(literature -> {
            List<String> tags = literatureMapper.selectLiteratureTags(literature.getLiteratureId());
            literature.setTags(tags);
        });
        
        return result;
    }

    @Override
    public String getLiteraturePdfUrl(Long literatureId, String userId) {
        if (literatureId == null) {
            throw new BizIllegalException("文献ID不能为空");
        }
        
        AiXLiterature literature = literatureMapper.selectById(literatureId);
        if (literature == null) {
            throw new BizIllegalException("文献不存在");
        }
        
        if (literature.getPdfUrl() == null || literature.getPdfUrl().isEmpty()) {
            throw new BizIllegalException("该文献没有PDF文件");
        }
        
        // 增加下载次数
        incrementDownloadCount(literatureId);
        
        return literature.getPdfUrl();
    }

    @Override
    public void incrementViewCount(Long literatureId) {
        if (literatureId != null) {
            literatureMapper.incrementViewCount(literatureId);
        }
    }

    @Override
    public void incrementDownloadCount(Long literatureId) {
        if (literatureId != null) {
            literatureMapper.incrementDownloadCount(literatureId);
        }
    }
    
    @Override
    @Transactional
    public R updateLiteratureCover(Long literatureId, MultipartFile coverFile) {
        // 检查文献是否存在
        AiXLiterature existingLiterature = literatureMapper.selectById(literatureId);
        if (existingLiterature == null) {
            throw new BadRequestException("文献不存在");
        }
        
        // 上传封面文件
        String coverUrl = ossService.uploadFileAndGetUrl(coverFile, "study-square-migrate", "literature/cover_" + System.currentTimeMillis() + "_" + coverFile.getOriginalFilename());
        
        // 更新文献封面
        AiXLiterature literature = new AiXLiterature();
        literature.setLiteratureId(literatureId);
        literature.setCoverUrl(coverUrl);
        literature.setUpdatedAt(LocalDateTime.now());
        
        int result = literatureMapper.updateById(literature);
        if (result > 0) {
            return R.ok();
        } else {
            throw new BadRequestException("更新文献封面失败");
        }
    }

    @Override
    public List<String> getLiteratureTags(Long areaId) {
        return tagConnectMapper.getLiteratureTags(areaId, 8);
    }
} 